package com.hanson.task;

import com.hanson.Const;
import com.hanson.common.bean.TaskBean;
import com.hanson.common.service.RedisService;
import com.hanson.entity.AcctbkSeqBean;
import com.hanson.entity.OrderBean;
import com.hanson.entity.SpreadMoneyBean;
import com.hanson.entity.UserBean;
import com.hanson.mapper.*;
import com.hanson.service.OrderService;
import com.hanson.service.SmsService;
import com.hanson.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 任务调度中心
 */
@Slf4j
@Component
public class TaskScheduled {
    @Autowired
    private TaskService taskService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private GoodsAttrValueBeanMapper goodsAttrValueBeanMapper;
    @Autowired
    private GoodsBeanMapper goodsBeanMapper;
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ScoreSeqBeanMapper scoreSeqBeanMapper;
    @Autowired
    private AcctbkSeqBeanMapper acctbkSeqBeanMapper;
    @Autowired
    private SpreadMoneyBeanMapper spreadMoneyBeanMapper;

    /**
     * 每分钟执行一次
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void scheduledTask() throws Exception {
        List<TaskBean> taskBeanList = taskService.getAllTask();
        if (CollectionUtils.isNotEmpty(taskBeanList)) {
            for (TaskBean taskBean : taskBeanList) {
                try {
                    if (taskBean.getJobType() == 1) {
                        doNotifyPay(taskBean);
                    } else if (taskBean.getJobType() == 2) {
                        autoFinishOrder(taskBean);
                    } else if (taskBean.getJobType() == 3) {
                        calculateSpreadMoney(taskBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("执行任务失败:" + taskBean.getJobType() + ":" + taskBean.getJobId(), e);
                }
            }
        }
    }

    /**
     * 订单确认一天后 计算佣金
     *
     * @param taskBean
     */
    @Transactional(rollbackFor = Exception.class)
    private synchronized void calculateSpreadMoney(TaskBean taskBean) {
        log.info("【调度任务 计算佣金 订单号：{}】", taskBean.getSystemId());
        List<SpreadMoneyBean> spreadMoneyBeanList = spreadMoneyBeanMapper.selectByOrderSeq(taskBean.getSystemId());
        if (CollectionUtils.isEmpty(spreadMoneyBeanList)) {
            log.info("【调度任务 计算佣金 找不到返佣数据：{}】 删除任务", taskBean.getSystemId());
            taskService.deleteTask(taskBean.getJobType(), taskBean.getJobId());
            return;
        }
        for (SpreadMoneyBean spreadMoneyBean : spreadMoneyBeanList) {
            if(spreadMoneyBean.getIsAccount() == 0){
                UserBean userBean = userBeanMapper.selectByOpenId(spreadMoneyBean.getOpenId());
                if (null != userBean) {
                    //佣金转账户
                    addUserMoney(userBean, spreadMoneyBean.getSpreadMoney(), null, spreadMoneyBean.getRemark());
                }
            }
        }
        //更新到账
        spreadMoneyBeanMapper.updateToAccountTimeAndStatus(new Date(), 1, taskBean.getSystemId());
        taskService.deleteTask(taskBean.getJobType(), taskBean.getJobId());
    }

    /**
     * 发货10天后自动确认订单
     *
     * @param taskBean
     */
    private void autoFinishOrder(TaskBean taskBean) throws Exception {
        Date currentDate = new Date();
        Date callTime = DateUtils.parseDate(taskBean.getCallTime(), "yyyy-MM-dd HH:mm:ss");
        boolean doFinishOrder = false;
        boolean doDelTask = false;
        List<OrderBean> orderBeanList = orderService.selectByOrderId(taskBean.getSystemId());
        if (CollectionUtils.isEmpty(orderBeanList)) {
            log.info("【调度任务 订单自动完成找不到订单：{}】 删除任务", taskBean.getSystemId());
            doDelTask = true;
        } else {
            int ordrerStatus = orderBeanList.get(0).getStatus();
            if (ordrerStatus == 5 || ordrerStatus == 7 || ordrerStatus == 8) {
                //已是完成状态
                doDelTask = true;
            } else {
                if (currentDate.after(callTime)) {
                    doFinishOrder = true;
                    doDelTask = true;
                }
            }
        }
        if (doFinishOrder) {
            orderService.finishOrder(taskBean.getSystemId());
        }
        if (doDelTask) {
            taskService.deleteTask(taskBean.getJobType(), taskBean.getJobId());
        }
    }

    /**
     * 支付提醒和取消未支付订单
     *
     * @param taskBean
     * @throws Exception
     */
    private void doNotifyPay(TaskBean taskBean) throws Exception {
        Date currentDate = new Date();
        Date callTime = DateUtils.parseDate(taskBean.getCallTime(), "yyyy-MM-dd HH:mm:ss");
        boolean doSms = false;
        boolean doDelOrder = false;
        boolean doDelTask = false;
        List<OrderBean> orderBeanList = orderService.selectByOrderId(taskBean.getSystemId());
        if (CollectionUtils.isEmpty(orderBeanList)) {
            log.info("【调度任务 订单支付提醒找不到订单：{}】 删除任务", taskBean.getSystemId());
            doDelTask = true;
        } else {
            int ordrerStatus = orderBeanList.get(0).getStatus();
            if (ordrerStatus == 1) {
                if (currentDate.after(callTime)) {
                    doDelOrder = true;
                    doDelTask = true;
                } else {
                    if (!taskBean.isSms() && DateUtils.addMinutes(currentDate, 10).after(callTime)) {
                        doSms = true;
                    }
                }
            } else {
                log.info("【调度任务 订单已支付删除任务：{}】", taskBean.getSystemId());
                doDelTask = true;
            }
        }
        if (doSms) {
            OrderBean orderBean = orderBeanList.get(0);
            smsService.payNofity(orderBean.getUserName(), orderBean.getUserPhone(), orderBean.getOrderId());
            taskBean.setSms(doSms);
            taskService.saveTask(taskBean);
        }
        if (doDelOrder) {
            orderService.deleteOrder(taskBean.getSystemId());
        }
        if (doDelTask) {
            taskService.deleteTask(taskBean.getJobType(), taskBean.getJobId());
        }
    }

    private void addUserMoney(UserBean userBean, Integer addMoney, String childId, String remark) {
        userBean.setMoney(userBean.getMoney() + addMoney);
        userBeanMapper.updateByPrimaryKeySelective(userBean);
        redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));

        AcctbkSeqBean acctbkSeqBean = new AcctbkSeqBean();
        acctbkSeqBean.setChildId(childId);
        acctbkSeqBean.setOpenId(userBean.getOpenId());
        acctbkSeqBean.setType(1);
        acctbkSeqBean.setCreateDate(new Date());
        acctbkSeqBean.setMoney(addMoney + "");
        acctbkSeqBean.setRemark(remark);
        acctbkSeqBeanMapper.insert(acctbkSeqBean);
    }
}
